package com.xlink.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Created by Cathy on 2015/12/21.
 */
@Controller("xlinkCodeController")
public class CodeController {
    int width = 80;
    int height = 25;
    int length = 4;
    int xx = 15;
    int codeY = 16;
    char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    int fontHeight = 20;
    @RequestMapping("/code")
    public void getCode(HttpServletRequest request, HttpServletResponse response)throws IOException {
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        Random rd = new Random();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
        g.setFont(font);
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        g.setColor(Color.BLACK);
        for (int i = 0; i < 40; i++) {
            int x = rd.nextInt(width);
            int y = rd.nextInt(height);
            int xl = rd.nextInt(12);
            int yl = rd.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }
        StringBuffer captcha = new StringBuffer();
        int red = 0, green = 0, blue = 0;
        for (int i = 0; i < length; i++) {
            String code = String.valueOf(codeSequence[rd.nextInt(36)]);
            red = rd.nextInt(255);
            green = rd.nextInt(255);
            blue = rd.nextInt(255);
            g.setColor(new Color(red, green, blue));
            g.drawString(code, (i + 1) * xx, codeY);
            captcha.append(code);
        }
        HttpSession session = request.getSession();
        System.out.print(captcha);
        session.setAttribute("code", captcha.toString());
        response.setContentType("image/jpeg");
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("expires", "0");
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(img, "jpeg", sos);
        sos.close();
    }
}
